﻿using B.S.RbacData.Domain;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using MediatR;
using System.Transactions;

namespace B.S.RbacData.Write.API.Applications.Commands.RBAC
{

    /// <summary>
    /// 编辑用户信息命令处理
    /// </summary>
    public class UpdateUserCommandHandlter : IRequestHandler<UpdateUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UserModel> userRep;
        private readonly IBaseRepository<UserRoleModel> userRoleRep;

        public UpdateUserCommandHandlter(IBaseRepository<UserModel> UserRep, IBaseRepository<UserRoleModel> userRoleRep)
        {
            userRep = UserRep;
            this.userRoleRep = userRoleRep;
        }


        public async Task<ApiResult<int>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {


            //分布式事务
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {

                try
                {

                    //修改用户信息
                    var user = userRep.GetAll().FirstOrDefault(x => x.ID == request.UserId);
                    user.UserName = request.UserName;
                    user.Password = request.Password;
                    user.UpdateTime = DateTime.Now;
                    await userRep.UpdateAsync(user);

                    //删除用户角色信息
                    var userrole = userRoleRep.GetAll().Where(x => x.UserId == request.UserId).ToList();
                    await userRoleRep.DeltelAll(userrole);

                    //新增用户角色信息
                    foreach (var RoleId in request.RoleIds)
                    {

                        UserRoleModel model = new UserRoleModel()
                        {

                            RoleId = RoleId,
                            UserId = request.UserId,
                            CreateTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            IsDeleted = false,
                            IsState = true,

                        };

                        await userRoleRep.AddAsync(model);

                    }

                    //提交事务
                    tran.Complete();

                }
                catch (Exception)
                {
                    //回滚事务
                    tran.Dispose();

                    throw;
                }


            }

            return new ApiResult<int>()
            {
                code = ResultEnumCode.Ok,
                data = 1,
                message = "编辑用户成功"

            };
        }
    }
}
